package ebj.common.annotation.demo_data_provider_manager.manager;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;

import ebj.common.annotation.demo_data_provider_manager.anno.AnnoProcessor;
import ebj.common.annotation.demo_data_provider_manager.anno.ProviderName;
import ebj.common.annotation.demo_data_provider_manager.data_provider.DataProvider;
import ebj.common.annotation.demo_data_provider_manager.exception.CustomException;

/**
 * <p>功能说明:...</p>
 * @author zhoushineyoung@hotmail.com
 * @time 2016年10月19日 上午11:09:46
 */
public class DataProviderManager {

    private static Map<String, Class<? extends DataProvider>> providers = new HashMap<>();

    static {
        String[] basePackages = {"ebj.common.annotation.demo_data_provider_manager"};
        providers = AnnoProcessor.getAllDataProviders(basePackages);
        System.out.println(JSONObject.toJSONString(providers));
    }

    public static Set<String> getProviderList() {
        return providers.keySet();
    }

    public static DataProvider getDataProvider(String type) throws InstantiationException, IllegalAccessException, CustomException {
        Class<?> clasz = providers.get(type.toLowerCase());
        if (null != clasz) {
            ProviderName providerName = (ProviderName) clasz.getAnnotation(ProviderName.class);
            if (providerName.value().equalsIgnoreCase(type)) {
                return (DataProvider) clasz.newInstance();
            }
        }
        throw new CustomException("DataProvider [" + type + "] Not Found");
    }

    protected static Class<? extends DataProvider> getDataProviderClass(String type) {
        return providers.get(type);
    }
}
